package com.bachongLightNovel.system.service.impl;

import com.bachongLightNovel.model.dto.system.AssignPermissionDto;
import com.bachongLightNovel.model.pojo.system.Role;
import com.bachongLightNovel.system.mapper.SystemRoleMapper;
import com.bachongLightNovel.system.mapper.SystemRolePermissionMapper;
import com.bachongLightNovel.system.mapper.SystemUserRoleMapper;
import com.bachongLightNovel.system.service.SystemRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SystemRoleServiceImpl implements SystemRoleService {


    @Autowired
    private SystemRoleMapper systemRoleMapper;

    @Autowired
    private SystemUserRoleMapper systemUserRoleMapper;

    @Autowired
    private SystemRolePermissionMapper systemRolePermissionMapper;

    /**
     * 获取角色列表
     * @return
     */
    @Override
    public List<Role> getRoleList() {
        List<Role> roleList=systemRoleMapper.selectAll();
        return roleList;
    }

    /**
     * 新增角色
     * @param role
     * @return
     */
    @Override
    public void saveRole(Role role) {
        systemRoleMapper.insert(role);
    }

    /**
     * 编辑角色
     * @param role
     * @return
     */
    @Override
    public void updateRole(Role role) {
        systemRoleMapper.update(role);
    }

    /**
     * 根据id删除角色
     * @param id
     * @return
     */
    @Override
    @Transactional
    public void removeRoleById(Long id) {
        systemRoleMapper.deleteById(id);
        //删除用户角色相关数据
        systemUserRoleMapper.deleteByRoleId(id);
        //删除角色权限相关数据
        systemRolePermissionMapper.deleteByRoleId(id);
    }

    /**
     * 根据用户id获取角色列表
     * @param
     * @return
     */
    @Override
    public List<Long> getRoleByUserId(Long userId) {
        List<Long> idList=systemUserRoleMapper.selectRoleIdsByUserId(userId);
        return idList;
    }

    /**
     * 为角色分配权限
     * @param dto :
     * @return Result
     */
    @Override
    @Transactional
    public void assignPermission(AssignPermissionDto dto) {
        //1.先删除之前相关数据
        systemRolePermissionMapper.deleteByRoleId(dto.getRoleId());
        //2.插入新的数据
        systemRolePermissionMapper.insertBatch(dto);
    }
}
